Component({
  properties: {},

  data: {
    columns: [], // 用于存储周区间
    selectedWeek: '' // 记录当前选择的周
  },

  lifetimes: {
    attached() {
      this.getTimer(); // 组件初始化时调用
    }
  },

  methods: {
    /**
     * 选择日期
     * @param {*} e 
     */
    onWeekChange(e) {
      const index = e.detail.value;
      this.setData({
        selectedWeek: this.data.columns[index] // 更新当前选中的周区间
      });
      console.log(this.data.selectedWeek, 99999);

      const result = this.parseWeekString(this.data.selectedWeek);
      console.log(`周数: ${result.weekNumber}`);
      console.log(`起始日期: ${result.startDate}`);
      console.log(`结束日期: ${result.endDate}`);

      // 触发自定义事件，通知父组件当前选择的周区间
      this.triggerEvent('weekSelected', {
        selectedWeek: this.data.selectedWeek,
        weekInfo: result
      });
    },

    /**
     * 处理日期
     */
    getTimer() {
      let time = new Date();
      let nowTime = time.getTime();
      let day = time.getDay();
      let oneDayTime = 24 * 60 * 60 * 1000;
      let MondayTime = nowTime - (day - 1) * oneDayTime;
      let SundayTime = nowTime + (7 - day) * oneDayTime;
      let setlist = [];
      for (let i = 0; i < 365; i += 7) {
        let weekNumber = this.getWeekNumber(new Date(MondayTime));
        let weekText = '第' + weekNumber + '周 ' + this.setTime(MondayTime) + '-' + this.setTime(SundayTime);
        setlist.push(weekText);

        time = new Date(time - oneDayTime * 7);
        nowTime = time.getTime();
        day = time.getDay();
        MondayTime = nowTime - (day - 1) * oneDayTime;
        SundayTime = nowTime + (7 - day) * oneDayTime;
      }
      let list = [...new Set(setlist)];
      this.setData({
        columns: list
      });
    },

    setTime(time) {
      let date = new Date(time);
      let yy = date.getFullYear();
      let m = date.getMonth() + 1;
      let day = date.getDate();
      let str = yy + '年' + (m < 10 ? '0' + m : m) + '月' + (day < 10 ? '0' + day : day) + '日';
      return str;
    },

    getWeekNumber(date) {
      const startOfYear = new Date(date.getFullYear(), 0, 1);
      const dayOfYear = ((date - startOfYear + (24 * 60 * 60 * 1000)) / (24 * 60 * 60 * 1000));
      return Math.ceil(dayOfYear / 7);
    },

    parseWeekString(weekStr) {
      const regex = /第(\d+)周\s(\d{4}年\d{2}月\d{2}日)-(\d{4}年\d{2}月\d{2}日)/;
      const match = weekStr.match(regex);
      if (match) {
        const weekNumber = match[1];
        const startDate = this.formatDate(match[2]);
        const endDate = this.formatDate(match[3]);
        return {
          weekNumber: weekNumber,
          startDate: startDate,
          endDate: endDate
        };
      } else {
        return null;
      }
    },

    formatDate(dateStr) {
      return dateStr.replace('年', '-').replace('月', '-').replace('日', '');
    }
  }
});
